package net.biancheng.framework.security.handle;

import com.alibaba.fastjson2.JSON;
import net.biancheng.common.constant.HttpStatus;
import net.biancheng.common.core.CommonResult;
import net.biancheng.common.model.LoginUser;
import net.biancheng.common.utils.ServletUtils;
import net.biancheng.framework.web.service.JwtTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: lb
 * @date: 2023/8/4 10:42
 * @desc: 退出成功处理类
 **/
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Autowired
    private JwtTokenService jwtTokenService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        LoginUser loginUser = jwtTokenService.getLoginUser(request);
        if (loginUser != null){
            // 删除用户缓存记录
            jwtTokenService.delLoginUser(loginUser.getUserKey());
        }
        ServletUtils.renderString(response, JSON.toJSONString(CommonResult.error(HttpStatus.SUCCESS, "退出成功")));
    }
}
